<template>
  <div class="exercise-practice">
    <div class="practice-header">
      <div class="progress-info">
        <span class="question-counter">题目 {{ currentIndex + 1 }}/{{ questions.length }}</span>
        <el-progress 
          :percentage="progressPercentage" 
          :stroke-width="10" 
          :format="() => ''" 
          class="progress-bar"
        />
      </div>
      <div class="timer" v-if="timerEnabled">
        <el-icon><Timer /></el-icon>
        <span>{{ formattedTime }}</span>
      </div>
    </div>

    <div class="question-container" v-if="currentQuestion">
      <div class="question-content">
        <h3 class="question-title">{{ currentQuestion.title }}</h3>
        <div class="question-description" v-html="currentQuestion.description"></div>
        
        <!-- 单选题 -->
        <div v-if="currentQuestion.type === 'single_choice'" class="options-container">
          <el-radio-group v-model="userAnswers[currentIndex]" class="radio-group">
            <el-radio 
              v-for="option in currentQuestion.options" 
              :key="option.id" 
              :label="option.id"
              class="option-item"
            >
              {{ option.text }}
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 多选题 -->
        <div v-else-if="currentQuestion.type === 'multiple_choice'" class="options-container">
          <el-checkbox-group v-model="userAnswers[currentIndex]" class="checkbox-group">
            <el-checkbox 
              v-for="option in currentQuestion.options" 
              :key="option.id" 
              :label="option.id"
              class="option-item"
            >
              {{ option.text }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        
        <!-- 填空题 -->
        <div v-else-if="currentQuestion.type === 'fill_blank'" class="fill-blank-container">
          <el-input
            v-model="userAnswers[currentIndex]"
            type="textarea"
            :rows="3"
            placeholder="请在此输入您的答案"
          />
        </div>
        
        <!-- 判断题 -->
        <div v-else-if="currentQuestion.type === 'true_false'" class="true-false-container">
          <el-radio-group v-model="userAnswers[currentIndex]" class="radio-group">
            <el-radio :label="true" class="option-item">正确</el-radio>
            <el-radio :label="false" class="option-item">错误</el-radio>
          </el-radio-group>
        </div>
      </div>
      
      <div class="question-feedback" v-if="showFeedback && currentFeedback">
        <div class="feedback-header" :class="currentFeedback.isCorrect ? 'correct' : 'incorrect'">
          <el-icon v-if="currentFeedback.isCorrect"><CircleCheckFilled /></el-icon>
          <el-icon v-else><CircleCloseFilled /></el-icon>
          <span>{{ currentFeedback.isCorrect ? '回答正确' : '回答错误' }}</span>
        </div>
        <div class="feedback-content">
          <div v-if="!currentFeedback.isCorrect" class="correct-answer">
            <div class="label">正确答案：</div>
            <div class="value" v-html="formatCorrectAnswer(currentQuestion)"></div>
          </div>
          <div class="explanation" v-if="currentQuestion.explanation">
            <div class="label">解析：</div>
            <div class="value" v-html="currentQuestion.explanation"></div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="practice-actions">
      <el-button 
        v-if="currentIndex > 0" 
        @click="previousQuestion"
        :disabled="submitting"
      >
        上一题
      </el-button>
      
      <el-button 
        v-if="!isLastQuestion" 
        type="primary" 
        @click="nextQuestion"
        :disabled="!canProceed || submitting"
      >
        {{ showFeedback ? '下一题' : '提交答案' }}
      </el-button>
      
      <el-button 
        v-if="isLastQuestion" 
        type="success" 
        @click="finishPractice"
        :disabled="!canProceed || submitting"
      >
        {{ showFeedback ? '完成练习' : '提交答案' }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { Timer, CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'

export default {
  name: 'ExercisePractice',
  components: {
    Timer,
    CircleCheckFilled,
    CircleCloseFilled
  },
  props: {
    questions: {
      type: Array,
      required: true
    },
    timerEnabled: {
      type: Boolean,
      default: false
    },
    showFeedbackImmediately: {
      type: Boolean,
      default: true
    }
  },
  emits: ['submit-answer', 'finish-practice', 'update-progress'],
  setup(props, { emit }) {
    const currentIndex = ref(0)
    const userAnswers = ref([])
    const showFeedback = ref(false)
    const feedbacks = ref([])
    const elapsedSeconds = ref(0)
    const timerInterval = ref(null)
    const submitting = ref(false)
    
    // 初始化答案数组
    const initializeAnswers = () => {
      userAnswers.value = props.questions.map(q => {
        if (q.type === 'multiple_choice') return []
        return null
      })
    }
    
    onMounted(() => {
      initializeAnswers()
      
      // 启动计时器
      if (props.timerEnabled) {
        timerInterval.value = setInterval(() => {
          elapsedSeconds.value++
        }, 1000)
      }
    })
    
    onBeforeUnmount(() => {
      if (timerInterval.value) {
        clearInterval(timerInterval.value)
      }
    })
    
    const currentQuestion = computed(() => {
      return props.questions[currentIndex.value] || null
    })
    
    const isLastQuestion = computed(() => {
      return currentIndex.value === props.questions.length - 1
    })
    
    const progressPercentage = computed(() => {
      return (currentIndex.value / props.questions.length) * 100
    })
    
    const formattedTime = computed(() => {
      const minutes = Math.floor(elapsedSeconds.value / 60)
      const seconds = elapsedSeconds.value % 60
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    })
    
    const currentFeedback = computed(() => {
      return feedbacks.value[currentIndex.value]
    })
    
    const canProceed = computed(() => {
      if (showFeedback.value) return true
      
      const answer = userAnswers.value[currentIndex.value]
      if (answer === null || answer === undefined) return false
      if (Array.isArray(answer) && answer.length === 0) return false
      return true
    })
    
    const formatCorrectAnswer = (question) => {
      if (!question) return ''
      
      switch (question.type) {
        case 'single_choice':
          const correctOption = question.options.find(o => o.id === question.correct_answer)
          return correctOption ? correctOption.text : ''
        
        case 'multiple_choice':
          return question.options
            .filter(o => question.correct_answer.includes(o.id))
            .map(o => o.text)
            .join('、')
        
        case 'fill_blank':
          return question.correct_answer
        
        case 'true_false':
          return question.correct_answer ? '正确' : '错误'
        
        default:
          return ''
      }
    }
    
    const checkAnswer = (questionIndex) => {
      const question = props.questions[questionIndex]
      const userAnswer = userAnswers.value[questionIndex]
      let isCorrect = false
      
      switch (question.type) {
        case 'single_choice':
        case 'true_false':
          isCorrect = userAnswer === question.correct_answer
          break
        
        case 'multiple_choice':
          // 检查数组是否包含相同的元素（不考虑顺序）
          isCorrect = Array.isArray(userAnswer) && 
                      Array.isArray(question.correct_answer) &&
                      userAnswer.length === question.correct_answer.length &&
                      userAnswer.every(a => question.correct_answer.includes(a))
          break
        
        case 'fill_blank':
          // 简单的字符串匹配，可以根据需要实现更复杂的匹配逻辑
          isCorrect = userAnswer && 
                      question.correct_answer && 
                      userAnswer.trim().toLowerCase() === question.correct_answer.trim().toLowerCase()
          break
      }
      
      return {
        questionId: question.id,
        userAnswer,
        correctAnswer: question.correct_answer,
        isCorrect
      }
    }
    
    const submitAnswer = async () => {
      if (submitting.value) return
      
      submitting.value = true
      const feedback = checkAnswer(currentIndex.value)
      
      try {
        // 发送答案到服务器
        await emit('submit-answer', {
          questionId: feedback.questionId,
          answer: feedback.userAnswer,
          isCorrect: feedback.isCorrect
        })
        
        // 更新反馈
        feedbacks.value[currentIndex.value] = feedback
        showFeedback.value = true
        
        // 更新进度
        const completedCount = feedbacks.value.filter(f => f).length
        const correctCount = feedbacks.value.filter(f => f && f.isCorrect).length
        
        emit('update-progress', {
          completed: completedCount,
          correct: correctCount,
          total: props.questions.length
        })
      } finally {
        submitting.value = false
      }
    }
    
    const nextQuestion = async () => {
      if (!showFeedback.value) {
        await submitAnswer()
        return
      }
      
      if (currentIndex.value < props.questions.length - 1) {
        currentIndex.value++
        showFeedback.value = false
      }
    }
    
    const previousQuestion = () => {
      if (currentIndex.value > 0) {
        currentIndex.value--
        showFeedback.value = !!feedbacks.value[currentIndex.value]
      }
    }
    
    const finishPractice = async () => {
      if (!showFeedback.value) {
        await submitAnswer()
        return
      }
      
      const completedCount = feedbacks.value.filter(f => f).length
      const correctCount = feedbacks.value.filter(f => f && f.isCorrect).length
      
      emit('finish-practice', {
        answers: userAnswers.value,
        feedbacks: feedbacks.value,
        timeSpent: elapsedSeconds.value,
        completedCount,
        correctCount,
        totalCount: props.questions.length,
        score: Math.round((correctCount / props.questions.length) * 100)
      })
    }
    
    return {
      currentIndex,
      userAnswers,
      showFeedback,
      feedbacks,
      elapsedSeconds,
      submitting,
      currentQuestion,
      isLastQuestion,
      progressPercentage,
      formattedTime,
      currentFeedback,
      canProceed,
      formatCorrectAnswer,
      submitAnswer,
      nextQuestion,
      previousQuestion,
      finishPractice
    }
  }
}
</script>

<style scoped>
.exercise-practice {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.practice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.question-counter {
  font-weight: 500;
  min-width: 80px;
}

.progress-bar {
  flex: 1;
}

.timer {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
  color: var(--el-color-primary);
}

.question-container {
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
  padding: 20px;
}

.question-title {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 16px;
}

.question-description {
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
}

.options-container {
  margin-top: 20px;
}

.radio-group,
.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  margin-right: 0;
  margin-left: 0;
  height: auto;
  padding: 8px 0;
}

.fill-blank-container {
  margin-top: 20px;
}

.question-feedback {
  margin-top: 20px;
  border-top: 1px solid var(--el-border-color-light);
  padding-top: 20px;
}

.feedback-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin-bottom: 12px;
  font-size: 16px;
}

.feedback-header.correct {
  color: var(--el-color-success);
}

.feedback-header.incorrect {
  color: var(--el-color-danger);
}

.feedback-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.correct-answer,
.explanation {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.label {
  font-weight: 500;
  color: var(--el-text-color-secondary);
}

.value {
  color: var(--el-text-color-primary);
}

.practice-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style> 